<?php
// JP Image EXIF Information View v1.6.0619
// Author: J.Parker / http://create74.com
// Translate: L.Ken / http://fall-leaf.net
require_once('lib/exif.inc');

function getImageExifView($target, $mother){
	global $blogid, $suri, $configVal;
	requireComponent('Textcube.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	getImageExifViewInitConfigVal($data);

	if(getAttachCheck_Exif(misc::getFileExtension($mother)) &&  $suri['directive']!="/rss" && $data['sImage']){
		$attachPath = ROOT."/attach/{$blogid}/".basename($mother);
		$contentWidth =	misc::getContentWidth();
		if (preg_match('/width="([1-9][0-9]*)"/i', $target, $temp)) {
			$tempWidth = ($temp[1] >= $contentWidth)?"":"width:{$temp[1]}px;";
		}
		switch($data['exifalign']){
			case 1: $data['exifalign'] = "left";	break;
			case 2:	$data['exifalign'] = "center";	break;
			case 3:	$data['exifalign'] = "right";	break;
			default: $data['exifalign'] = "center";
		}
		if(getExifImage($attachPath , 0)){
			$target .= "<div style=\"margin:0 auto;{$tempWidth}\">";
			$target .= "<div class=\"ExifView\" style=\"{$tempWidth}\">";
			$target .= getExifImage($attachPath , 0);
			$target .= "</div></div>";

		}
	}
	return $target;
}

function getFreeImageExifView($target, $mother){
	global $blogid, $suri, $configVal;
	requireComponent('Textcube.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	getImageExifViewInitConfigVal($data);

	$tempImages = preg_match_all('/<img[^>]+?src=("|\')?([^\'">]*?)("|\')([^>]*)>/si', $target, $temp);
	if($tempImages && $data['fImage']){
		for ($i=0; $i<$tempImages; $i++){
			$substrCount = substr_count($temp[4][$i], '=');
			if((strpos(strtolower($temp[2][$i]), 'http://') !== 0) && ($substrCount < 4)){
				if(getAttachCheck_Exif(misc::getFileExtension($temp[2][$i])) &&  $suri['directive']!="/rss"){
					$attachPath = ROOT."/attach/{$blogid}/".basename($temp[2][$i]);
					$contentWidth =	misc::getContentWidth();
					if($data['exifwidth'] == 2){
						if (preg_match('/width="([1-9][0-9]*)"/i', $temp[0][$i], $imageInfo)) {
							$imageWidth = $imageInfo[1];
						}else{
							$imageInfo = getimagesize($attachPath);
							$imageWidth = $imageInfo[0];
						}
						$tempWidth = ($imageWidth >= $contentWidth)?"":"width:".$imageWidth."px;";
					}else{
						$tempWidth = "";
					}
					switch($data['exifalign']){
						case 1:		$data['exifalign'] = "left";	break;
						case 2:		$data['exifalign'] = "center";	break;
						case 3:		$data['exifalign'] = "right";	break;
						default:	$data['exifalign'] = "center";
					}
					if(getExifImage($attachPath , 0)){
						$exifInfo = "<div style=\"{$tempWidth}\">";
						$exifInfo .= $temp[0][$i]."<div class=\"ExifView\" style=\"{$tempWidth}\">";
						$exifInfo .= getExifImage($attachPath , 0);
						$exifInfo .= "</div></div>";
						$target = str_replace($temp[0][$i], $exifInfo, $target);
					}
				}
			}
		}
	}
	return $target;
}

function getExifImage($filePath,$verbose){
	global  $configVal;
	requireComponent('Textcube.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	getImageExifViewInitConfigVal($data);

	$exifResult = read_exif_data_raw($filePath, 0);

	if(isset($exifResult)){
		$exifInfo = array();
		$spacer = "<span class=\"exifSP\"> | </span>";
		if(isset($exifResult['SubIFD']['ExposureBiasValue'])){
			$evtmp = split(" ", $exifResult['SubIFD']['ExposureBiasValue']);
			$exifResult['SubIFD']['ExposureBiasValue'] = ((round($evtmp[0],2) > 0)? '+': '').round($evtmp[0],2).$evtmp[1];
		}
		if(isset($exifResult['SubIFD']['WhiteBalance'])){
			$exifResult['SubIFD']['WhiteBalance'] = ($exifResult['SubIFD']['WhiteBalance']==0)?"Auto W/B":"Manual W/B";
		}
		if(isset($exifResult['SubIFD']['FNumber'])){
			$fntmp = split(" ", $exifResult['SubIFD']['FNumber']);
			$exifResult['SubIFD']['FNumber'] = $fntmp[0].round($fntmp[1],2);
		}
		if(isset($exifResult['IFD0']['Make'])					&& isset($data['ex1'])  && !empty($data['ex1']))	array_push($exifInfo, getDecode($exifResult['IFD0']['Make']));										// 1.제조사
		if(isset($exifResult['IFD0']['Model'])					&& isset($data['ex2'])  && !empty($data['ex2']))	array_push($exifInfo, getDecode($exifResult['IFD0']['Model']));										// 2.모델
		if(isset($exifResult['SubIFD']['ExposureProgram'])		&& isset($data['ex3'])  && !empty($data['ex3']))	array_push($exifInfo, getDecode($exifResult['SubIFD']['ExposureProgram']));							// 3.촬영모드
		if(isset($exifResult['SubIFD']['MeteringMode'])			&& isset($data['ex4'])  && !empty($data['ex4']))	array_push($exifInfo, getDecode($exifResult['SubIFD']['MeteringMode']));							// 4.측광모드
		if(isset($exifResult['SubIFD']['WhiteBalance'])			&& isset($data['ex5'])  && !empty($data['ex5']))	array_push($exifInfo, $exifResult['SubIFD']['WhiteBalance']);										// 5.화이트밸런스
		if(isset($exifResult['SubIFD']['ExposureTime'])			&& isset($data['ex6'])  && !empty($data['ex6']))	array_push($exifInfo, getReduceExif($exifResult['SubIFD']['ExposureTime']).'sec');					// 6.셔터속도
		if(isset($exifResult['SubIFD']['FNumber'])				&& isset($data['ex7'])  && !empty($data['ex7']))	array_push($exifInfo, strtoupper($exifResult['SubIFD']['FNumber']));								// 7.조리개값
		if(isset($exifResult['SubIFD']['MaxApertureValue'])		&& isset($data['ex8'])  && !empty($data['ex8']))	array_push($exifInfo, strtoupper(str_replace(" ","",$exifResult['SubIFD']['MaxApertureValue'])));	// 8.최대 조리개값
		if(isset($exifResult['SubIFD']['ExposureBiasValue'])	&& isset($data['ex9'])  && !empty($data['ex9']))	array_push($exifInfo, $exifResult['SubIFD']['ExposureBiasValue']);									// 9.노출보정
		if(isset($exifResult['SubIFD']['FocalLength'])			&& isset($data['ex10']) && !empty($data['ex10']))	array_push($exifInfo, str_replace(" ","",$exifResult['SubIFD']['FocalLength']));					// 10.초점거리
		if(isset($exifResult['SubIFD']['FocalLengthIn35mmFilm'])&& isset($data['ex11']) && !empty($data['ex11']))	array_push($exifInfo, '35mm equiv '.$exifResult['SubIFD']['FocalLengthIn35mmFilm'].'mm');			// 11.35mm 초점거리
		if(isset($exifResult['SubIFD']['ISOSpeedRatings'])		&& isset($data['ex12']) && !empty($data['ex12']))	array_push($exifInfo, 'ISO-'.$exifResult['SubIFD']['ISOSpeedRatings']);								// 12.ISO값
		if(isset($exifResult['SubIFD']['Flash'])				&& isset($data['ex13']) && !empty($data['ex13']))	array_push($exifInfo, $exifResult['SubIFD']['Flash']);												// 13.플래쉬사용
		if(isset($exifResult['SubIFD']['DateTimedigitized'])	&& isset($data['ex14']) && !empty($data['ex14']))	array_push($exifInfo, getDecode($exifResult['SubIFD']['DateTimedigitized']));						// 14.촬영시각
		if(isset($exifResult['SubIFD']['ExifImageWidth']) && isset($exifResult['SubIFD']['ExifImageHeight'])	&& isset($data['ex15']) && !empty($data['ex15']))	array_push($exifInfo, str_replace(" pixels", "", $exifResult['SubIFD']['ExifImageWidth'] . " x " . $exifResult['SubIFD']['ExifImageHeight']) . " pixels");			// 15.사진크기

		$exifValue = ($exifInfo)?"  <span class=\"exifIF\">" . implode("</span>{$spacer}<span class=\"exifIF\">", $exifInfo) . "</span>":NULL;
	}
	return $exifValue;
}

function getDecode($str){
	$str = str_replace(array("<",">"), array("",""), $str);
	$str = utf8_decode($str);
	$str = trim($str);
	return $str;
}

function getImageExifViewStyle($target){
	global $configVal;
	requireComponent('Textcube.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	getImageExifViewInitConfigVal($data);

	switch($data['exifalign']){
		case 1:	$data['exifalign'] = "left";	break;
		case 2:	$data['exifalign'] = "center";	break;
		case 3:	$data['exifalign'] = "right";	break;
		default: $data['exifalign'] = "center";
	}
	ob_start();
?>
<style type="text/css">
	/* Exif Data CSS Setting */
	.ExifView {margin:<?php echo $data['exifmargin'];?>;padding:<?php echo $data['exifpadding'];?>; font:<?php echo $data['exifsize'];?> <?php echo $data['exiffont'];?>;color:<?php echo $data['exifcolor'];?>;text-align:<?php echo $data['exifalign'];?>;white-space: normal;}
	.ExifView .exifIF {display:inline;white-space:normal;}
	.ExifView .exifSP {font:7pt Arial;color:#ccc;margin:0px 0px 0px 0px;display:inline;white-space:normal;}
</style>
<?php
	$target .= ob_get_contents();
	ob_end_clean();
	return $target;
}

function getAttachCheck_Exif($ext){
	if (in_array($ext, array('jpg','jpeg','png'))) return true;
	else return false;
}

function getImageExifViewInitConfigVal(&$data){
	$data['sImage'] = isset($data['sImage']) ? $data['sImage'] : 1;
	$data['fImage'] = isset($data['fImage']) ? $data['fImage'] : 1;
	$data['exifwidth'] = isset($data['exifwidth']) ? $data['exifwidth'] : 2;
	$data['exifmargin'] = isset($data['exifmargin']) ? $data['exifmargin'] : "5px 0px 0px 0px";
	$data['exifpadding'] = isset($data['exifpadding']) ? $data['exifpadding'] : "0px 0px 0px 0px";
	$data['exiffont'] = isset($data['exiffont']) ? $data['exiffont'] : "tahoma";
	$data['exifsize'] = isset($data['exifsize']) ? $data['exifsize'] : "7pt";
	$data['exifcolor'] = isset($data['exifcolor']) ? $data['exifcolor'] : "#777777";
	$data['exifalign'] = isset($data['exifalign']) ? $data['exifalign'] : 2;
	for($i=1; $i <= 15; $i++){
		$data['ex'.$i] = isset($data['ex'.$i]) ? $data['ex'.$i] : 1;
	}
}

function getReduceExif($exifvalue){
	$exifvalue = str_replace(array("sec", ""), array("",""), $exifvalue);
	$vals = split("/",$exifvalue);
	if(count($vals) == 2){
		$exposure = round($vals[0]/$vals[1],2);
		if($exposure < 1) $exposure = "1/".round($vals[1]/$vals[0],0);
	}else{
		$exposure = $vals[0];
		if($exposure < 1 && $exposure != 0) $exposure = "1/".round(1/$vals[0],0);
	}
	return $exposure;
}

function ImageExifViewDataSet($DATA){
	requireComponent('Textcube.Function.misc');
	$cfg = misc::fetchConfigVal($DATA);
	
	switch (getBlogSetting('language')) {
		case 'zh-TW':
			$msg1="::選擇錯誤::\n\n照片EXIF適用範圍至少選擇一個。   ";
			$msg2="::選擇錯誤::\n\n必須選擇一個顯示照片EXIF信息寬度大小的方法   ";
		break;
		case 'zh-CN':
			$msg1="::选择错误::\n\n照片EXIF适用范围至少选择一个。   ";
			$msg2="::选择错误::\n\n必须选择一个显示照片EXIF信息宽度大小的方法   ";
		break;
		default:
			$msg1="::선택 오류::\n\n사진 EXIF 적용 범위는 적어도 하나이상 선택하셔야 합니다.   ";
			$msg2="::선택 오류::\n\n사진 EXIF 정보의 가로크기 표시 방법을 선택하셔야 합니다.   ";
	}
	
	if(!$cfg['sImage'] && !$cfg['fImage']) return $msg1;
	if(!$cfg['exifwidth']) return $msg2;
	return true;
}
?>